package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient esClient;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * GET product/_search
     * {
     * "query":{
     * "bool":{
     * "must":[
     * {
     * "match":{
     * "skuTile":"小米"
     * }
     * },
     * ],
     * //     *             分类，品牌等都可以是过滤条件(不参与评分，速度更快)
     * "filter":[
     * {
     * "term":{
     * "hasStock":true
     * }
     * },
     * {
     * "term":{
     * "catalogId":"225
     * }
     * },
     * {
     * "terms":{
     * "brandId":[
     * "1",
     * "2",
     * ]
     * }
     * },
     * {
     * //     *                  属性是嵌入式类型(es mapping中的类型)，需要使用嵌入式查询
     * "nested":{
     * "path":"attrs",
     * "query":{
     * "bool":{
     * "must":[
     * {
     * "term":{
     * "attrs.attrId":{
     * "value":"15"
     * }
     * }
     * } ,{
     * "terms":{
     * "attrs.attrValue":[
     * "海思",
     * "晓龙"
     * ]
     * }
     * }
     * ]
     * }
     * }
     * }
     * },{
     * "range":{
     * "skuPrice":{
     * "get":"1000",
     * "lte":"2000"
     * }
     * }
     * }
     * ]
     * }
     * },{
     * "sort":{
     * "skuPrice":{
     * "order":"desc"
     * }
     * }
     * },
     * "from":0,
     * "size":5,
     * "highlight":{
     * "fields":{
     * "skuTile":{}
     * }
     * "pre_tags":"<b style='color:red'>",
     * "poet_tag":"</b>"
     * },{
     * "aggs":{  聚合分析
     * "brand_agg":{   聚合品牌id
     * "terms":{
     * "field":"brandId",
     * "size":10
     * },
     * "aggs":{  子聚合 在上一步根据品牌id聚合基础上，再根据品牌名称聚合
     * "brand_name_agg":{
     * "terms":{
     * "field":"brandName",
     * "size":10
     * }
     * },
     * "brand_img_agg":{
     * "terms":{
     * "filed":"brandImg",
     * "size":10
     * }
     * }
     * }
     * },
     * "catalog_agg":{
     * "terms":{
     * "field":"catalogId",
     * "size":10
     * },
     * "aggs":{
     * "catalog_name_agg":{
     * "terms":{
     * "field":"catalogName",
     * "size":10
     * }
     * }
     * }
     * },{
     * 聚合出所有的查询结果的属性值及属性名
     * "attr_aggs":{
     * "nested":{  嵌入式类型聚合也需要使用嵌入式
     * "path":"attrs",
     * "aggs":{
     * "attr_id":{
     * "terms":{
     * "filed":"attrs.attrId",
     * "size":10
     * },
     * "aggs":{
     * "attr_name_aggs":{
     * "terms":{
     * "filed":"attrs.attrName",
     * "size":10
     * }
     * },
     * "attr_value_aggs":{
     * "terms":{
     * "filed":"attrs.attrValue",
     * "size":10
     * }
     * }
     * }
     * }
     * }
     * }
     * }
     * }
     * }
     * }
     * }
     * <p>
     * <p>
     * <p>
     * 模糊匹配 ，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析(查询出来的结果涉及到的可过滤的条件)
     *
     * @param param
     * @return
     */
    @Override
    public SearchResult search(SearchParam param) {
//准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);


        try {
//            执行检索请求
            SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);

//            分装响应数据
            return buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();  //构建dsl语句

        /**
         * 模糊 匹配，过滤
         */
//        1构建boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyWord())) {
//            1.1 must模糊匹配
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTile", param.getKeyWord()));
        }
//        1.2构建filter
        if (param.getCatalog3Id() != null) {
//        1.2.1三级分类的filter
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
//        1.2.2按照品牌id查询(多个)
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
//        1.2.3按照属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
//            attrs=1_其他:安卓&attrs=2_5寸:6寸
            for (String attrString : param.getAttrs()) {
//                attrs=1_其他:安卓
                String[] s = attrString.split("_");
                String attrId = s[0];
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] attrValues = s[1].split(":");//属性检索值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
//                每一个都必须生成一个嵌入式查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
//        1.2.4按照是否有库存查询
        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

//        1.2.5按照价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
//            "range":{
//                "skuPrice":{
//                    "get":"1000",
//                    "lte":"2000"
//                }
//            }
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                } else {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }

        sourceBuilder.query(boolQueryBuilder);

        /**
         * 排序
         * 高亮
         */

//        2.1排序
        if (!StringUtils.isEmpty(param.getSort())) {
//            排序
            /**
             * 排序条件
             * saleCount_asc  / saleCount_desc
             *
             * skuPrice  asc/desc 价格
             *
             * hostScore acs/desc 热度
             */
            String[] s = param.getSort().split("_");
            if ("asc".equalsIgnoreCase(s[1])) {
                sourceBuilder.sort(s[0], SortOrder.ASC);
            } else {
                sourceBuilder.sort(s[0], SortOrder.DESC);
            }
        }

//        2.2分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
//        2.3高亮
        if (!StringUtils.isEmpty(param.getKeyWord())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");

            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
//        3.1 品牌聚合brand_agg

//        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
//        brand_agg.field("brandId").size(10);
        TermsAggregationBuilder brand_agg = aggTerms("brand_agg", "brandId", 10);
//        3.1.1 子聚合 brand_name_agg
//        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
//        brand_name_agg.field("brandName").size(1);
        brand_agg.subAggregation(aggTerms("brand_name_agg", "brandName", 1));
//      3.1.2子聚合
//        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg");
//        brand_img_agg.field("brandImg").size(10);
        brand_agg.subAggregation(aggTerms("brand_img_agg", "brandImg", 10));

        sourceBuilder.aggregation(brand_agg);

//        3.2 分类聚合
//        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
//        catalog_agg.field("catalogId").size(1);
        TermsAggregationBuilder catalog_agg = aggTerms("catalog_agg", "catalogId", 1);

//        3.2.1子聚合
//        TermsAggregationBuilder catalog_name_agg = AggregationBuilders.terms("catalog_name_agg");
//        catalog_name_agg.field("catalogName").size(1);
        catalog_agg.subAggregation(aggTerms("catalog_name_agg", "catalogName", 1));

        sourceBuilder.aggregation(catalog_agg);

//        3.3属性聚合
        NestedAggregationBuilder attr_aggs = AggregationBuilders.nested("attr_aggs", "attrs");
//        3.3.1嵌入子聚合
//        TermsAggregationBuilder attr_id = AggregationBuilders.terms("attr_id");
//        attr_id.field("attrs.attrId").size(1);
        TermsAggregationBuilder attr_id = aggTerms("attr_id", "attrs.attrId", 1);
//        3.3.2 子聚合的子聚合
//        TermsAggregationBuilder attr_name_aggs = AggregationBuilders.terms("attr_name_aggs");
//        attr_name_aggs.field("attrs.attrName").size(1);
        attr_id.subAggregation(aggTerms("attr_name_aggs", "attrs.attrName", 1));

//        TermsAggregationBuilder attr_value_aggs = AggregationBuilders.terms("attr_value_aggs");
//        attr_value_aggs.field("attrs.attrValue").size(50);
        attr_id.subAggregation(aggTerms("attr_value_aggs", "attrs.attrValue", 50));

        attr_aggs.subAggregation(attr_id);


        sourceBuilder.aggregation(attr_aggs);

        String dsl = sourceBuilder.toString();
        System.out.println("构建的dsl语句 : " + dsl);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    private TermsAggregationBuilder aggTerms(String name, String field, int size) {
        TermsAggregationBuilder aggs = AggregationBuilders.terms(name);
        aggs.field(field).size(size);
        return aggs;
    }


    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult searchResult = new SearchResult();
//        封装所有查询到的商品
        SearchHits hits = response.getHits();
        if (hits != null && hits.getHits().length > 0) {
            List<SkuEsModel> products = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
//                每一天命中记录
                String source = hit.getSourceAsString();
                TypeReference<SkuEsModel> skuEsModelTypeReference = new TypeReference<SkuEsModel>() {
                };

                SkuEsModel model = JSON.parseObject(source, skuEsModelTypeReference);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (param.getKeyWord() != null && highlightFields != null && highlightFields.size() > 0) {
                    HighlightField skuTitle = highlightFields.get("skuTitle");
                    Text fragment = skuTitle.getFragments()[0];
                    model.setSkuTitle(fragment.toString());
                }
                products.add(model);
            }
            searchResult.setProducts(products);
        }
//        分类信息
        Aggregations aggregations = response.getAggregations();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        if (catalog_agg != null) {

            List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
            if (buckets != null && buckets.size() > 0) {
                List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
                for (Terms.Bucket bucket : buckets) {
                    SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
//                    分类id
                    String keyAsString = bucket.getKeyAsString();
                    catalogVo.setCatalogId(Long.parseLong(keyAsString));

                    ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                    String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                    catalogVo.setCatalogName(catalogName);

                    catalogVos.add(catalogVo);
                }
                searchResult.setCatalogs(catalogVos);
            }
        }

//        品牌信息
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        if (brand_agg != null) {
            List<? extends Terms.Bucket> buckets = brand_agg.getBuckets();
            if (buckets != null && buckets.size() > 0) {
                for (Terms.Bucket bucket : buckets) {
                    SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                    brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));

                    ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
                    if (brand_name_agg != null) {
                        brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
                    }

                    ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
                    if (brand_img_agg != null) {
                        brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
                    }

                    brandVoList.add(brandVo);
                }

            }
            searchResult.setBrands(brandVoList);
        }

//        属性信息
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attr_aggs = aggregations.get("attr_aggs");
        ParsedLongTerms attr_id = attr_aggs.getAggregations().get("attr_id");
        if (attr_id != null) {
            List<? extends Terms.Bucket> buckets = attr_id.getBuckets();
            if (buckets != null && buckets.size() > 0) {
                for (Terms.Bucket bucket : buckets) {
                    SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
//                    属性id
                    long attrId = bucket.getKeyAsNumber().longValue();
                    attrVo.setAttrId(attrId);
//                    属性名称
                    ParsedStringTerms attr_name_aggs = bucket.getAggregations().get("attr_name_aggs");
                    if (attr_name_aggs != null) {
                        attrVo.setAttrName(attr_name_aggs.getBuckets().get(0).getKeyAsString());
                    }
//                    属性所有值
                    ParsedStringTerms attr_value_aggs = bucket.getAggregations().get("attr_value_aggs");
                    if (attr_value_aggs != null) {
                        List<String> collect = attr_value_aggs.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
                        attrVo.setAttrValue(collect);
                    }
                    attrVoList.add(attrVo);
                }
            }
        }

        searchResult.setAttrs(attrVoList);

//        分页信息
        TotalHits totalHits = hits.getTotalHits();
        if (totalHits != null) {
            long total = totalHits.value;
            searchResult.setTotal(total);
            long totalPages = total % EsConstant.PRODUCT_PAGE_SIZE == 0 ? (total / EsConstant.PRODUCT_PAGE_SIZE) : (total / EsConstant.PRODUCT_PAGE_SIZE + 1);
            searchResult.setTotalPages((int) totalPages);
        }
        searchResult.setPageNum(param.getPageNum());
        if(param.getAttrs()!=null&&param.getAttrs().size() > 0){

            List<SearchResult.NavVo> navVoList = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
//            分析attr参数值构建navVo
                String[] s = attr.split("_");
//              TODO  可以从聚合结果中拿到
                R attrInfo = productFeignService.info(Long.parseLong(s[0]));
                if(attrInfo.getCode() == 0){
                    TypeReference<AttrResponseVo> typeReference = new TypeReference<AttrResponseVo>(){};
                    AttrResponseVo attrResponseVo = attrInfo.getData(typeReference);
                    navVo.setNavName(attrResponseVo.getAttrName());
                }else{
                    navVo.setNavName("");
                }
                navVo.setNavValue(s[1]);
//          取消面包屑后要跳转的页
//            拿到所有的查询条件，去掉选中的面包屑
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "Utf-8");
                    encode = encode.replaceAll("\\+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("attrs=&"+encode, "");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            searchResult.getNavs().addAll(navVoList);
        }

//        if(param.getBrandId()!=null&&param.getBrandId().size() > 0){
//            SearchResult.NavVo navVo = new SearchResult.NavVo();
//
//            navVo.setNavName("品牌");
//            navVo.setNavName("");
//
//        }

        return searchResult;
    }
}
